<?php
class pvuvLog
{
	private $startTime;//访问开始时间
	private $endTime;//访问结束时间
	private $kmReferer;//记录referer页面
	private $kmUA;//记录浏览器等
	private $kmViewurl;//完整的访问url
	private $kmViewTime;
	private $kmIp;
	private $kmCid;
	private $conn;
	public $visitWeixinID='';
	private $tableName = 'urls_pv_log';//默认的表名
	public $kmResult='';
	private $kmFrom;
	public $urlID = '';
	private $srcWeixinID;
	public function __construct($key='test',$splitFlag=false,$debug=false){
		$this->start();
		if(!$debug)
		{
			$this->conn = mysql_connect("localhost", "root", "weicedbmojito160824", true);
			mysql_select_db($key."_pv_log",$this->conn);
		}else
		{
            $this->conn = mysql_connect("localhost", "root", "weicedbmojito160824", true);
            mysql_select_db($key."_pv_log",$this->conn);
		}
		$query = "Set Names 'utf8mb4'";
		mysql_query($query,$this->conn);
		if($splitFlag)
		{
			$tableName = $this->tableName . date("Ymd",time());
			if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '$tableName'",$this->conn))==1)
			{
				$this->tableName = $tableName;
			}
		}
		$this->kmReferer = isset($_SERVER["HTTP_REFERER"]) ? mysql_real_escape_string($_SERVER["HTTP_REFERER"]) : "";
		$this->kmUA = isset($_SERVER["HTTP_USER_AGENT"]) ? mysql_real_escape_string($_SERVER['HTTP_USER_AGENT']) : "";
		$this->kmViewurl = mysql_real_escape_string("http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
		$this->kmViewTime = date("Y-m-d H:i:s",time());
		$this->kmIp = $this->getClientIP();
		$this->kmCid = $this->getUid();
		$this->srcWeixinID = isset($_GET['srcopenid']) ? mysql_real_escape_string($_GET['srcopenid']) : "";
		$this->kmFrom = isset($_GET['from']) ? mysql_real_escape_string($_GET['from']) : ''; 
	}
	private function getMicrotime()
	{
		list($usec, $sec) = explode(' ', microtime());
        return ((float)$usec + (float)$sec);
	}
	private function start()
	{
		$this->startTime = $this->getMicrotime();
	}
	private function end()
	{
		$this->endTime = $this->getMicrotime();
	}
	private function spent()
	{
		return round(($this->endTime - $this->startTime) * 1000, 1);
	}
	//IP地址归化
	private function ipFilter($key)
	{
		$key = preg_replace("/[^0-9.]/", "", $key);
		return preg_match("/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/", $key) ? $key :
        "0.0.0.0";
	}

	//获取客户端ip
	private function getClientIP()
	{
		$ipstr = "";
		if (isset($_SERVER['HTTP_CLIENT_IP']) and !empty($_SERVER['HTTP_CLIENT_IP']))
		{
			$ipstr .= $this->ipFilter($_SERVER['HTTP_CLIENT_IP']) . ",";
		}
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) and !empty($_SERVER['HTTP_X_FORWARDED_FOR']))
		{
			$ipstr .= $_SERVER['HTTP_X_FORWARDED_FOR'] . ",";
		}
		if (isset($_SERVER['HTTP_PROXY_USER']) and !empty($_SERVER['HTTP_PROXY_USER']))
		{
			$ipstr .= $this->ipFilter($_SERVER['HTTP_PROXY_USER']) . ",";
		}
		if (isset($_SERVER['REMOTE_ADDR']) and !empty($_SERVER['REMOTE_ADDR']))
		{
			$ipstr .= $this->ipFilter($_SERVER['REMOTE_ADDR']) . ",";
		}

		$ip = strtok($ipstr, ",");
		do
		{
			$ip = trim($ip);
			if (empty($ip))
			{
				continue;
			}

			$ip = ip2long($ip);

			//-------------------
			// skip private ip ranges
			//-------------------
			// 10.0.0.0 - 10.255.255.255
			// 172.16.0.0 - 172.31.255.255
			// 192.168.0.0 - 192.168.255.255
			// 127.0.0.1, 255.255.255.255, 0.0.0.0
			//-------------------
			if (!(($ip == 0) or ($ip == (int)0xFFFFFFFF) or ($ip == 0x7F000001) or (($ip >=
            0x0A000000) and ($ip <= 0x0AFFFFFF)) or (($ip >= (int)0xC0A80000) and ($ip <= (int)
            0xC0A8FFFF)) or (($ip >= (int)0xAC100000) and ($ip <= (int)0xAC1FFFFF))))
			{
				return long2ip($ip);
			}
		} while ($ip = strtok(','));

		//      return "0.0.0.0";
		return $this->ipFilter($_SERVER['REMOTE_ADDR']);
	}
	//生成uid
	private function generateUid($ip)
	{
		$output = md5(md5($ip) . md5(time()));
		$rand_str = "" . (mt_rand(0, 10000));
		return substr($output, strlen($rand_str)) . $rand_str;
	}
	//获取uid
	private function getUid()
	{
		if (isset($_COOKIE["kmcid"]))
		{
			$uid = $_COOKIE["kmcid"];
		} else
		{
			$uid = $this->generateUid($this->getClientIP());
			//SetCookie("kmcid", $uid, time() + 3600 * 24 * 365 * 20, "/", ".kmsocial.cn");
			SetCookie("kmcid", $uid, time() + 3600 * 24 * 365 * 20, "/", "");
		}
		return $uid;
	}
	public function saveLog()
	{
		$this->end();
		$sql = "insert into $this->tableName (urlID, visitWeixinID, srcWeixinID, result, dealTime, viewTime, ip, kmcid, referUrl, userAgent, url, weixinFrom) ";
		$sql .= " values ('$this->urlID', '$this->visitWeixinID', '$this->srcWeixinID', '$this->kmResult', '".$this->spent()."', '$this->kmViewTime', '$this->kmIp', '$this->kmCid', '$this->kmReferer', '$this->kmUA', '$this->kmViewurl', '$this->kmFrom')";
		mysql_query($sql, $this->conn);
		mysql_close($this->conn);
	}
}
?>